
    
    
    
    
    
    // 设备连接参数
        const clientId = '6886edbba72147363d93bdb4_webduan1_0_0_2025081202';
        const username = '6886edbba72147363d93bdb4_webduan1';
        const password = '4a0dcd96def9a222bde6e7d47396d5c05b99e784f7a491f884a630f0783843f3';
        const hostname = '2766b7c2d2.st1.iotda-device.cn-south-1.myhuaweicloud.com';
        const port = 443; // 使用WebSocket端口

        // 要订阅的主题
        const topics = [
            'etcRevice',
            'traffic_signs',
            'ArchitectureLighting',
            '5hweb',
            'testone',
            'jiguangleida'
            
        ];

        // 全局变量
        let client = null;
        let isConnected = false;  // 连接华为云的状态
        const statusElement = document.querySelector('.status');
        var jianzhudenguang_shuju=[]  //建筑灯光的集体数据
        
        var jiaotongbiaozhi_shuju=[]  //交通标志的集体数据
    
      
        var honglundeng_shuju=[]  //红绿灯的集体数据
     

       


   


      
        



        let etc = {};  //etc--------------------------------------------------------
        let etcnniou  = 1//当前按钮的号
        let etcduan = true;  //判断第一次 一个成功了就不判断了
        //etc
        const etcquanbushuju= document.getElementById('etcquanbushuju'); //全部设备
        const etcdangqianshebei= document.getElementById('etcdangqianshebei'); //当前设备号
        const etczhuangtai= document.getElementById('etczhuangtai'); //在线状态
        const etcdangqianshebeiqianmian= document.getElementById('etcdangqianshebeiqianmian'); //当前设前面号
        const etcdangqianshebeihoumian= document.getElementById('etcdangqianshebeihoumian'); //当前设前面号
        // etc左按钮点击 减法
        function etczuodianji(){
          //按键的值
          var jianzhi = Object.keys(etc)//jian值
          var zhongchangdu = Object.keys(etc).length; //总数
          etcnniou = etcnniou-1
          if(etcnniou < 1){
            etcnniou = zhongchangdu
          }

          //判断当前值的前面值
          var jiaotongbiaoziqian = etcnniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
          //console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = etcnniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
          //console.log(jianzhi[jiaotongbiaohoumian-1])
          etcdangqianshebeiqianmian.textContent =jianzhi[jiaotongbiaoziqian-1]
          etcdangqianshebeihoumian.textContent =jianzhi[jiaotongbiaohoumian-1]
          //console.log(jiaotongbiaozianniou)
        }
          // etc又按钮点击 加法
        function etcyoudianji(){
          var jianzhi = Object.keys(etc)//jian值
          var zhongchangdu = Object.keys(etc).length; //总数
          etcnniou = etcnniou + 1
          if(etcnniou >zhongchangdu){
            etcnniou = 1
          }

           //判断当前值的前面值
          var jiaotongbiaoziqian = etcnniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
          console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = etcnniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
         //console.log(jianzhi[jiaotongbiaohoumian-1])
          etcdangqianshebeiqianmian.textContent =jianzhi[jiaotongbiaoziqian-1]
          etcdangqianshebeihoumian.textContent =jianzhi[jiaotongbiaohoumian-1]

          //console.log(jiaotongbiaozianniou)
        }


        let jianzhudengguang = {};  //建筑灯光----------------------------------------
         let jianzhuanniou =1//当前按钮的号
        let jianzhupanduan = true;  //判断第一次 一个成功了就不判断了
        //建筑灯光
        const jiaotongzxian= document.getElementById('jiaotongzxian'); //全部设备
        const jiaotongdangqian= document.getElementById('jiaotongdangqian'); //当前设备号
        const jiaotongqianmianshebei= document.getElementById('jiaotongqianmianshebei'); //当前前
        const jiaotonghoumianshebei= document.getElementById('jiaotonghoumianshebei'); //当前设后
        const jiaotongmoshi= document.getElementById('jiaotongmoshi'); //在线状态 图片
        const jiaotongwenzhi= document.getElementById('jiaotongwenzhi'); //在线状态 文字
    
         // 建筑灯光左按钮点击 减法
        function juanzhuzuodianji(){
                //按键的值
          var jianzhi = Object.keys(jianzhudengguang)//jian值
          var zhongchangdu = Object.keys(jianzhudengguang).length; //总数
          jianzhuanniou = jianzhuanniou-1
          if(jianzhuanniou < 1){
            jianzhuanniou = zhongchangdu
          }

          //判断当前值的前面值
          var jiaotongbiaoziqian = jianzhuanniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
          //console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = jianzhuanniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
          //console.log(jianzhi[jiaotongbiaohoumian-1])
          jiaotongqianmianshebei.textContent =jianzhi[jiaotongbiaoziqian-1]
          jiaotonghoumianshebei.textContent =jianzhi[jiaotongbiaohoumian-1]
          //console.log(jiaotongbiaozianniou)

        }
            // 建筑灯光按钮点击 加法
        function jianzhuzuodianji(){
           var jianzhi = Object.keys(jianzhudengguang)//jian值
          var zhongchangdu = Object.keys(jianzhudengguang).length; //总数
          jianzhuanniou = jianzhuanniou + 1
          if(jianzhuanniou >zhongchangdu){
            jianzhuanniou = 1
          }

           //判断当前值的前面值
          var jiaotongbiaoziqian = jianzhuanniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
          //console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = jianzhuanniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
         //console.log(jianzhi[jiaotongbiaohoumian-1])
         jiaotongqianmianshebei.textContent =jianzhi[jiaotongbiaoziqian-1]
          jiaotonghoumianshebei.textContent =jianzhi[jiaotongbiaohoumian-1]

          //console.log(jiaotongbiaozianniou)
        }


        let honglundeng = {};  //红绿灯----------------------------------------------
        let honglundengnniou =1//当前按钮的号
        let honglundengduan = true;  //判断第一次 一个成功了就不判断了
        // 红绿灯
         const xiangzuo= document.getElementById('xiangzuo'); //左转图片
         const xiangqian= document.getElementById('xiangqian'); //直行图片
         const xiangyou= document.getElementById('xiangyou'); //右转图片
         const honglundengshuzi= document.getElementById('honglundengshuzi'); //大的中间倒计时
         const honglunshebeuigeshu= document.getElementById('honglunshebeuigeshu'); //总的在线设备个数 
         const honglundangqianshebei= document.getElementById('honglundangqianshebei'); //当前的设备号
         const honglunzuozuobian= document.getElementById('honglunzuozuobian'); //左边数字
         const honglunzuoyoubian= document.getElementById('honglunzuoyoubian'); //右边数字
        // 红绿灯左按钮点击 减法
        function honglundengzuodianji(){
          //按键的值
          var jianzhi = Object.keys(honglundeng)//jian值
          var zhongchangdu = Object.keys(honglundeng).length; //总数
          honglundengnniou = honglundengnniou-1
          if(honglundengnniou < 1){
            honglundengnniou = zhongchangdu
          }

          //判断当前值的前面值
          var jiaotongbiaoziqian = honglundengnniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
          //console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = honglundengnniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
          //console.log(jianzhi[jiaotongbiaohoumian-1])
          honglunzuozuobian.textContent =jianzhi[jiaotongbiaoziqian-1]
          honglunzuoyoubian.textContent =jianzhi[jiaotongbiaohoumian-1]
          //console.log(jiaotongbiaozianniou)
        }
            // 红绿灯又按钮点击 加法
        function honglundengzuodianji(){
          var jianzhi = Object.keys(honglundeng)//jian值
          var zhongchangdu = Object.keys(honglundeng).length; //总数
          honglundengnniou = honglundengnniou + 1
          if(honglundengnniou >zhongchangdu){
            honglundengnniou = 1
          }

           //判断当前值的前面值
          var jiaotongbiaoziqian = honglundengnniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
         // console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = honglundengnniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
         //console.log(jianzhi[jiaotongbiaohoumian-1])
          honglunzuozuobian.textContent =jianzhi[jiaotongbiaoziqian-1]
          honglunzuoyoubian.textContent =jianzhi[jiaotongbiaohoumian-1]

          //console.log(jiaotongbiaozianniou)
        }       


        let jiaotongbiaozhi = {};  //交通标志---------------------------------------------------------
        let jiaotongbiaozianniou = 1;//当前按钮的号
        let jiaotongpanduan = true;  //判断第一次 一个成功了就不判断了
        //交通标志变量
        const jiaotongtupian= document.getElementById('jiaotongtupian'); //实时显示图片
        const jiaotongquanbushebei= document.getElementById('jiaotongquanbushebei'); //在线全部设备
        const jiaotongdangqianhao= document.getElementById('jiaotongdangqianhao'); //       当前设备
        const jiaotongdangqianmoshi= document.getElementById('jiaotongbiaoziqianmian'); //交通标子前面值
        const jiaotongdizhi= document.getElementById('jiaotongbiaozihoumian'); //交通标子后面值
             // 交通标志左按钮点击 减法
        function jiaotongzuodianji(){
          //按键的值
          var jianzhi = Object.keys(jiaotongbiaozhi)//jian值
          var zhongchangdu = Object.keys(jiaotongbiaozhi).length; //总数
          jiaotongbiaozianniou = jiaotongbiaozianniou-1
          if(jiaotongbiaozianniou < 1){
            jiaotongbiaozianniou = zhongchangdu
          }

          //判断当前值的前面值
          var jiaotongbiaoziqian = jiaotongbiaozianniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
          //console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = jiaotongbiaozianniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
          //console.log(jianzhi[jiaotongbiaohoumian-1])
          jiaotongdangqianmoshi.textContent =jianzhi[jiaotongbiaoziqian-1]
          jiaotongdizhi.textContent =jianzhi[jiaotongbiaohoumian-1]
          //console.log(jiaotongbiaozianniou)
        }
          // 交通标志又按钮点击 加法
        function jiaotongyoudianji(){
          var jianzhi = Object.keys(jiaotongbiaozhi)//jian值
          var zhongchangdu = Object.keys(jiaotongbiaozhi).length; //总数
          jiaotongbiaozianniou = jiaotongbiaozianniou + 1
          if(jiaotongbiaozianniou >zhongchangdu){
            jiaotongbiaozianniou = 1
          }

           //判断当前值的前面值
          var jiaotongbiaoziqian = jiaotongbiaozianniou-1
           if(jiaotongbiaoziqian < 1){
            jiaotongbiaoziqian = zhongchangdu
          }
          console.log(jianzhi[jiaotongbiaoziqian-1])
            //判断当前值的后面值
          var jiaotongbiaohoumian = jiaotongbiaozianniou+1
          if(jiaotongbiaohoumian >zhongchangdu){
            jiaotongbiaohoumian = 1
          }
         //console.log(jianzhi[jiaotongbiaohoumian-1])
          jiaotongdangqianmoshi.textContent =jianzhi[jiaotongbiaoziqian-1]
          jiaotongdizhi.textContent =jianzhi[jiaotongbiaohoumian-1]

          //console.log(jiaotongbiaozianniou)
        }


        //4H小车实时数据
    
        let xiaoche = {};  //小车
        let xiaocheanniou = 1; //小车的按钮
         const xiaocheshebeihao=document.getElementById('xiaocheshebeihao');  //小车的号码

        const dianjidianya=document.getElementById('dianjidianya');  //电机电压：12V
        const shuchudianliou=document.getElementById('shuchudianliou');  //电机输出电流：8A
        const dianjizhankongbi=document.getElementById('dianjizhankongbi');  //电机占空比：50
        const dianjizhuanshu=document.getElementById('dianjizhuanshu');  //电机转速：20prm
        const dianjiwendu=document.getElementById('dianjiwendu');  //电机温度：10℃
        const dianjidianliou=document.getElementById('dianjidianliou');  //电机电流：10A

        const qianduojidianya=document.getElementById('qianduojidianya');  //前舵机电压
        const qianduojiwendu=document.getElementById('qianduojiwendu');  //前舵机温度
        const qianduojidianliou=document.getElementById('qianduojidianliou');  //前舵机电流
        const qianduojiweizhi=document.getElementById('qianduojiweizhi');  //前舵机位置  
        const qianduojiweitiaozhi=document.getElementById('qianduojiweitiaozhi');  //前舵机微调值
        //向前点击跟换设备
        function xiaochezuojiantou(){
            //按键的值
          var jianzhi = Object.keys(xiaoche)//jian值
          var zhongchangdu = Object.keys(xiaoche).length; //总数
          xiaocheanniou = xiaocheanniou-1
          if(xiaocheanniou < 1){
            xiaocheanniou = zhongchangdu
          }
        };  
        //向后点击跟换设备
         function xiaocheyouzhuan(){
            var jianzhi = Object.keys(xiaoche)//jian值
          var zhongchangdu = Object.keys(xiaoche).length; //总数
          xiaocheanniou = xiaocheanniou + 1
          if(xiaocheanniou >zhongchangdu){
            xiaocheanniou = 1
          }
         };   
         

        let xioache_jiguangleida = {}  //小车的激光雷达 ----------------------------------------------------------------
        //4h小车位置
      
        const xiaocheweizi1 = document.getElementById('4hxiaocheweizi1');    //4h小车实时改变的位置
        const xiaocheweizi2 = document.getElementById('4hxiaocheweizi2');    //4h小车实时改变的位置
        const xiaocheweizi3 = document.getElementById('4hxiaocheweizi3');    //4h小车实时改变的位置

        xiaocheweizi3.style.top = "0px"; // 距离父元素顶部100px
        xiaocheweizi3.style.left = "30px"; // 距离父元素左侧200px   

        xiaocheweizi2.style.top = "0px"; // 距离父元素顶部100px
        xiaocheweizi2.style.left = "110px"; // 距离父元素左侧200px    

        xiaocheweizi1.style.top = "0px"; // 距离父元素顶部100px
        xiaocheweizi1.style.left = "70px"; // 距离父元素左侧200px    .
        
       
  


   

        var etc_shuju=[]  //etc的集体数据

         // 页面加载前执行的函数
        function onPageLoad() {
            handleClick()
        }
         // 页面关闭或刷新前执行的函数
        function onPageUnload(event) {
            // 判断是刷新还是关闭
            if (event.currentTarget.performance.navigation.type === 1) {
                  console.log('页面正在刷新！');
                  handleClick()
            } else {
               duankai()
                // 关闭时的处理逻辑
            }
            
            // 可以在这里添加确认提示（部分浏览器可能不支持自定义消息）
            event.preventDefault();
            event.returnValue = '您确定要离开吗？';
            return event.returnValue;
        }
        document.addEventListener('DOMContentLoaded', onPageLoad);
        
        // 或者使用 load 事件 - 整个页面（包括图片等资源）加载完成时触发（较晚）
        // window.addEventListener('load', onPageLoad);

        // 注册页面卸载事件（关闭或刷新）
        window.addEventListener('beforeunload', onPageUnload);
        // 连接华为云IoT函数
        function handleClick() {
            console.log('尝试连接设备...')
            // 如果已经连接则返回
            if (isConnected) return;

            // 构建WebSocket连接地址
            const connectUrl = `wss://${hostname}:${port}/mqtt`;

            // 连接选项
            const options = {
                clientId: clientId,
                username: username,
                password: password,
                clean: true,
                connectTimeout: 4000,
                keepalive: 60
            };

            // 创建客户端实例并连接
            client = mqtt.connect(connectUrl, options);

            // 连接成功处理
            client.on('connect', () => {
                isConnected = true;
                updateUI();
                console.log('✅ 成功连接到华为云IoT');
                
                // 订阅主题
                client.subscribe(topics, { qos: 1 }, (err) => {
                    if (!err) {
                        console.log('📋 已成功订阅以下主题:', topics);
                    } else {
                        console.error('❌ 订阅主题失败:', err);
                    }
                });
            });

         
            
            // 接收消息处理
            client.on('message', (topic, message) => {
                const time = new Date().toLocaleTimeString();
                //  console.log(`\n[${time}] 收到主题 [${topic}] 的消息:`);
                //   console.log('内容:', message.toString());
                //建筑灯光消息-----------------------------------
                if(topic == 'ArchitectureLighting'){    
                  // console.log(`\n[${time}] 收到主题 [${topic}] 的消息:`);
                  // console.log('内容:', message.toString());
                 const jsonData = JSON.parse(message.toString());  //解析后的json数据
                   //把01变成1
                   num = parseInt(jsonData.services[0].properties.设备号, 10);
                   jianzhudengguang[num] =jsonData.services[0].properties
                  // 判断当前模式
                //   var  dangqianmoshi1
                  if(jsonData.services[0].properties.模式 == 1){
                     jianzhudengguang[num].状态名称 =  '呼吸灯';
                     jianzhudengguang[num].图片lianjie = "./img/建筑灯光/呼吸灯.png";
                  }
                  else if(jsonData.services[0].properties.模式 == 2){
                       jianzhudengguang[num].状态名称 = '长亮';
                       jianzhudengguang[num].图片lianjie = "./img/建筑灯光/长亮.png";
                  }
                  else if(jsonData.services[0].properties.模式 == 3){
                       jianzhudengguang[num].状态名称 =  '关闭';
                       jianzhudengguang[num].图片lianjie = "./img/建筑灯光/关灯.png";
                  }
                  //console.log(jianzhudengguang)

                 
                //  console.log(keys)
                 // console.log(jianzhudengguang)


                    //查询当前点击的数组库               
                      //console.log(dangqian,'000000000000000000000000000000000000')  //交通标志所以信息
                     
                      const keys = Object.keys(jianzhudengguang); // 直接得到键数组 ["name", "age", "type"]
                      //console.log(keys,"全部建的名字")  //全部建的名字
                      var geshu = keys.length;     //全部在线的的设备++++++++++++
                      // console.log(geshu,"全部在线的的设备") 
                      //  console.log(jiaotongbiaozhi)
                      var dangqianjian = keys[jianzhuanniou-1]  //当前按钮的建
                
                      // console.log(jiaotongbiaozhi)
                      // console.log(dangqianjian)
                   

                        var dangqianshuzu = jianzhudengguang[dangqianjian]
                   //   console.log(dangqianshuzu)
                   
                       
                        jiaotongzxian.textContent = geshu;   //全部设备
                        jiaotongdangqian.textContent = dangqianjian;  //当前设备号码
                        
                        jiaotongmoshi.src = dangqianshuzu.图片lianjie      //当前图片
                        jiaotongwenzhi.textContent = dangqianshuzu.状态名称      //当前文字
              
                 
                }
            //    //etc消息-----------------------------------  
                else if(topic == 'etcRevice'){           
                //  console.log(`\n[${time}] 收到主题 [${topic}] 的消息:`);
                //   console.log('内容:', message.toString());
                 const jsonData = JSON.parse(message.toString()); //解析后的json数据
                //console.log(jsonData.json_message)
                //把01变成1
                  num = parseInt(jsonData.json_message.Equipment_number, 10);
                  
                  etc[num] = jsonData.json_message  //保存全部数据

                 // console.log(etc)



                  const keys = Object.keys(etc); // 直接得到键数组 ["name", "age", "type"]
                      //console.log(keys,"全部建的名字")  //全部建的名字
                      var geshu = keys.length;     //全部在线的的设备++++++++++++
                      // console.log(geshu,"全部在线的的设备") 
                      //  console.log(jiaotongbiaozhi)
                      var dangqianjian = keys[etcnniou-1]  //当前按钮的建

                      var dangqianshuzu = etc[dangqianjian]
                    //  console.log(dangqianshuzu)
                      var tupianlianjie 
                      if(dangqianshuzu.Mode==1){
                        tupianlianjie='./img/背景加栏车杆/拦车开启1.png'
                      }else{
                         tupianlianjie='./img/背景加栏车杆/拦车关闭.png'
                      }

                        etcquanbushuju.textContent =geshu;//全部设备
                        etcdangqianshebei.textContent =dangqianjian; //当前设备号
                        etczhuangtai.src =tupianlianjie;//在线状态
                  


          
                  
                }     
              //交通标志消息-----------------------------------
                else if(topic=='traffic_signs'){  
          
                  // console.log('内容:', message.toString());
                 const jsonData = JSON.parse(message.toString());  //解析后的json数据

                     //把01变成1
                   num = parseInt(jsonData.services[0].properties.设备号, 10);
                    // console.log(num)
                    //查看返回的数据数据库有没有
                    var linshishuju = {}
                    // jianzhudengguang[num] = jsonData.services[0].properties                           
                    switch(jsonData.services[0].properties.模式) {
                      case 1:
                          linshishuju.图片文字 = '左转';
                          linshishuju.链接 = "./img/1左转02.jpg";                    
                        break; // 跳出switch语句
                      case 2:
                         linshishuju.图片文字 = '直行';
                         linshishuju.图片链接 =  "./img/2直行02.jpg";
                        break;
                      // 可以有更多case
                      case 3:
                          linshishuju.图片文字  = '右转';
                              linshishuju.链接  =  "./img/3right01.jpg";
                        break;
                      case 4:
                           linshishuju.图片文字  = '停车场';
                             linshishuju.链接  =  "./img/4停车场01.png";
                        break;
                      case 5:
                             linshishuju.图片文字  =  '人行道';
                             linshishuju.链接  =  "./img/5人行道01.jpg";
                        break;
                      case 6:
                            linshishuju.图片文字  =  '直行右转';
                             linshishuju.链接  =   "./img/6直行右转01.jpg";                      
                        break;
                      case 7:
                            linshishuju.图片文字  = '直行左转';
                              linshishuju.链接  =   "./img/7直行左转01.jpg";                      
                        break;
                      case 8:
                             linshishuju.图片文字 =  '停止';
                             linshishuju.链接  = "./img/停止.jpg";                      
                        break;
                      case 9:
                           linshishuju.图片文字 =  '限速20';
                            linshishuju.链接 =  "./img/9限速2001.jpg";                    
                        break;
                      case 10:
                             linshishuju.图片文字  =  '禁止左转';
                            linshishuju.链接 =  "./img/10禁止左转01.jpg";                     
                        break;
                      case 11:
                               linshishuju.图片文字  =  '禁止直行';
                             linshishuju.链接 = "./img/11禁止直行01.jpg";                     
                        break;
                      case 12:
                               linshishuju.图片文字  =   '禁止右转';
                            linshishuju.链接  =  "./img/12禁止右转01.jpg";                   
                        break;
                      default:
                              linshishuju.图片文字  = '离线';
                    };
            
                    const mergedData1 = Object.assign({}, jsonData.services[0].properties, linshishuju);
                    jiaotongbiaozhi[num] = mergedData1
                    
                      //查询当前点击的数组库               
                      //console.log(dangqian,'000000000000000000000000000000000000')  //交通标志所以信息
                     
                      const keys = Object.keys(jiaotongbiaozhi); // 直接得到键数组 ["name", "age", "type"]
                      //console.log(keys,"全部建的名字")  //全部建的名字
                      var geshu = keys.length;     //全部在线的的设备++++++++++++
                      // console.log(geshu,"全部在线的的设备") 
                      //  console.log(jiaotongbiaozhi)
                      var dangqianjian = keys[jiaotongbiaozianniou-1]  //当前按钮的建
                      
                      // console.log(jiaotongbiaozhi)
                      // console.log(dangqianjian)
                   

                        var dangqianshuzu = jiaotongbiaozhi[dangqianjian]
                       // console.log(dangqianshuzu)
                        jiaotongquanbushebei.textContent = geshu;    //修改设备的总个数
                        jiaotongdangqianhao.textContent = dangqianjian;    //当前设备号
                        //jiaotongdangqianmoshi.textContent = dangqianshuzu.图片文字;    //图片文字
                        //jiaotongdizhi.textContent = dangqianshuzu.地区;    //理工大学
                        jiaotongtupian.src = dangqianshuzu.链接;    //修改图片
                        
                }      
               //红绿灯消息----------------------------------
                else if(topic=='testone'){           
                //   console.log(`\n[${time}] 收到主题 [${topic}] 的消息:`);
                //   console.log('内容:', message.toString());
                  const jsonData = JSON.parse(message.toString()); //解析后的json数据 
                  var shebeihao =  parseInt(jsonData.services[0].properties.设备号, 10); //设备号                

                    var linshi = jsonData.services[0].properties;
                    var diyi1 = '';  //第一个灯
                    var dier2 = '';  //第二个灯
                    var disan3 = '';  //第三个灯
                    var zhiti4 = '';  //字体颜色              
                    if(jsonData.services[0].properties.模式 == 3){    //常绿色
                      diyi1= "./img/红绿灯/向左箭头_绿色.png";
                      dier2 = "./img/红绿灯/向上箭头_绿色.png";                 
                      disan3 = "./img/红绿灯/向右箭头_绿色.png";  
                      zhiti4 =  "green";    
                    }
                    else if(jsonData.services[0].properties.模式 == 2){ //长黄
                     diyi1 = "./img/红绿灯/向左箭头_黄色.png";
                     dier2 =  "./img/红绿灯/向上箭头_黄色.png";                 
                     disan3 = "./img/红绿灯/向右箭头_黄色.png";   
                     zhiti4  =  "yellow";  
                    }
                    else if(jsonData.services[0].properties.模式 == 1){  //长红
                      diyi1 = "./img/红绿灯/向左箭头_红色.png";
                     dier2 =  "./img/红绿灯/向上箭头_红色.png";                 
                     disan3 = "./img/红绿灯/向右箭头_红色.png";     
                      zhiti4 =  "red";  
                    }
                     else if(jsonData.services[0].properties.模式 == 0){  //一个灯亮
                          if(jsonData.services[0].properties.灯组==1){  //左灯亮
                                     if(jsonData.services[0].properties.阶段 == 0){  //绿灯
                                      diyi1 = "./img/红绿灯/向左箭头_红色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_绿色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_红色.png";   
                                      zhiti4 =  "green";  
                                      }
                                      else if(jsonData.services[0].properties.阶段 ==1) //黄灯
                                      {
                                      diyi1 = "./img/红绿灯/向左箭头_红色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_黄色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_红色.png";  
                                      zhiti4 =  "yellow";                                  
                                      } 
                          }
                          else if(jsonData.services[0].properties.灯组==2){//中间灯亮
                               
                                  if(jsonData.services[0].properties.阶段 == 0){  //绿灯
                                    diyi1 = "./img/红绿灯/向左箭头_红色.png";
                                    dier2 =  "./img/红绿灯/向上箭头_红色.png";                 
                                    disan3 = "./img/红绿灯/向右箭头_绿色.png";  
                                    zhiti4 =  "green";  
                                    }
                                    else if(jsonData.services[0].properties.阶段 ==1) //黄灯
                                    {
                                    diyi1 = "./img/红绿灯/向左箭头_红色.png";
                                    dier2 =  "./img/红绿灯/向上箭头_红色.png";                 
                                    disan3 = "./img/红绿灯/向右箭头_黄色.png";  
                                    zhiti4 =  "yellow";                                  
                                    }                      
                                                              }
                          else if(jsonData.services[0].properties.灯组==0){//右灯亮
                                     if(jsonData.services[0].properties.阶段 == 0){  //绿灯                                  
                                      diyi1 = "./img/红绿灯/向左箭头_绿色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_红色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_红色.png";                                       
                                      zhiti4=  "green";  
                                      }
                                      else if(jsonData.services[0].properties.阶段 ==1) //黄灯
                                      {
                                      diyi1 = "./img/红绿灯/向左箭头_黄色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_红色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_红色.png";                                         
                                      zhiti4 =  "yellow";                                  
                                      }  
                          }
                                 
                     }
                      else if(jsonData.services[0].properties.模式 == 4){  //两个灯亮
                           if(jsonData.services[0].properties.灯组 == 2){
                            if(jsonData.services[0].properties.阶段 == 0){  //绿灯
                                      diyi1 = "./img/红绿灯/向左箭头_绿色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_红色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_绿色.png";  
                                      zhiti4 =  "green";  
                            }
                            else if(jsonData.services[0].properties.阶段 ==1) //黄灯red
                            {
                                      diyi1 = "./img/红绿灯/向左箭头_黄色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_红色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_黄色.png";  
                                      zhiti4 =  "yellow";                                  
                            }  
                        }
                        else if(jsonData.services[0].properties.灯组 == 0){
                                     if(jsonData.services[0].properties.阶段 == 0){  //绿灯
                                      diyi1 = "./img/红绿灯/向左箭头_绿色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_绿色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_红色.png";   
                                      zhiti4 =  "green";  
                                      }
                                      else if(jsonData.services[0].properties.阶段 ==1) //黄灯
                                      {
                                      diyi1 = "./img/红绿灯/向左箭头_黄色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_黄色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_红色.png";    
                                      zhiti4=  "yellow";                                  
                                      } 
                        }
                        else if(jsonData.services[0].properties.灯组 == 1){
                                     if(jsonData.services[0].properties.阶段 == 0){  //绿灯
                                      diyi1 = "./img/红绿灯/向左箭头_红色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_绿色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_绿色.png";                                          
                                      zhiti4 =  "green";  
                                      }
                                      else if(jsonData.services[0].properties.阶段 ==1) //黄灯
                                      {
                                      diyi1 = "./img/红绿灯/向左箭头_红色.png";
                                      dier2 =  "./img/红绿灯/向上箭头_黄色.png";                 
                                      disan3 = "./img/红绿灯/向右箭头_黄色.png";   
                                      zhiti4 =  "yellow";                                  
                                      }                          
                        }

                     }
                     linshi.第一个灯 = diyi1
                     linshi.第二个灯 = dier2
                     linshi.第三个灯 = disan3
                     linshi.文字颜色 = zhiti4

                     honglundeng[shebeihao] = linshi
                     //console.log(honglundeng)

                           
                      const keys = Object.keys(honglundeng); // 直接得到键数组 ["name", "age", "type"]
                      //console.log(keys,"全部建的名字")  //全部建的名字
                      var geshu = keys.length;     //全部在线的的设备++++++++++++
                      // console.log(geshu,"全部在线的的设备") 
                      //  console.log(jiaotongbiaozhi)
                      var dangqianjian = keys[honglundengnniou-1]  //当前按钮的建
                      
                      // console.log(jiaotongbiaozhi)
                      // console.log(dangqianjian)
                   

                        var dangqianshuzu = honglundeng[dangqianjian]
                       console.log(dangqianshuzu)
                   
                        //给前端赋值honglundeng
                    console.log(honglundeng[honglundengnniou],'+++++++++++++++++++++++++')
                    xiangzuo.src =     dangqianshuzu.第一个灯          //第一个灯
                    xiangqian.src =     dangqianshuzu.第二个灯    //第二个灯
                    xiangyou.src =    dangqianshuzu.第三个灯   //第三个灯
                    honglundengshuzi.textContent =  dangqianshuzu.倒计时    //文字                    
                    honglunshebeuigeshu.textContent = geshu  //设备中共在线个数
                    honglundangqianshebei.textContent = dangqianjian  //当前设备号
      
                         

                    // }


                  

                }  
                // 4h小车数据
                else if(topic == "5hweb"){
                  // console.log(`\n[${time}] 收到主题 [${topic}] 的消息:`);
                  // console.log('内容:', message.toString());
                  const jsonData = JSON.parse(message.toString());
                 // console.log(jsonData.services[0].properties)
                  const properties = jsonData.services[0].properties;
                    //console.log(properties)
                  // 创建一个数组用于存储键值对
                 const keyValueArray = [];
                  
                  //遍历properties对象的每个键
                  for (const key in properties) {
                    // 检查是否是对象自身的属性（非继承来的）
                    if (properties.hasOwnProperty(key)) {
                      // 将键和值以数组形式存入（也可以用对象形式 {key, value: properties[key]}）
                      keyValueArray.push([key, properties[key]]);
                    }
                  }
                  xiaocheshuju = {} //保存临时数据
                  
                
                xiaocheshuju.设备号 = keyValueArray[0][1]    //设备号
                xiaocheshuju.时间 =  keyValueArray[1][1]  //时间
                xiaocheshuju.电机电压 =   keyValueArray[2][1] //电机电压：12V
                xiaocheshuju.电机输出电流 =  keyValueArray[3][1] //电机输出电流：8A
                xiaocheshuju.电机占空比 =   keyValueArray[4][1] //电机占空比：50
                xiaocheshuju.电机转速 =   keyValueArray[5][1]//电机转速：20prm
                xiaocheshuju.电机温度 = keyValueArray[6][1]  //电机温度：10℃

                xiaocheshuju.电机电流 = keyValueArray[7][1]  //电机电流：10A
                xiaocheshuju.前舵机电压 = keyValueArray[8][1] //前舵机电压
                xiaocheshuju.前舵机温度 = keyValueArray[9][1]  //前舵机温度
                xiaocheshuju.前舵机电流 =  keyValueArray[10][1]  //前舵机电流
                xiaocheshuju.前舵机位置 = keyValueArray[11][1]  //前舵机位置
                xiaocheshuju.前舵机微调值 = keyValueArray[12][1]  //前舵机微调值
                  //数据保存到全局变量
                 xiaoche[keyValueArray[0][1]] = xiaocheshuju
            
                  
                   
                      const keys = Object.keys(xiaoche); // 直接得到键数组 ["name", "age", "type"]
                      //console.log(keys,"全部建的名字")  //全部建的名字
                      var geshu = keys.length;     //全部在线的的设备++++++++++++
                      // console.log(geshu,"全部在线的的设备") 
                      //  console.log(jiaotongbiaozhi)
                      var dangqianjian = keys[xiaocheanniou-1]  //当前按钮的建
                      
                      // console.log(jiaotongbiaozhi)
                      // console.log(dangqianjian)
                   

                        var dangqianshuzu = xiaoche[dangqianjian]

                       xiaocheshebeihao.textContent = dangqianjian;    //小车的号码
                       dianjidianya.textContent = dangqianshuzu.电机电压;    //电机电压：12V
                       shuchudianliou.textContent = dangqianshuzu.电机输出电流;    //电机输出电流：8A
                       dianjizhankongbi.textContent = dangqianshuzu.电机占空比;    ////电机占空比：50
                       dianjizhuanshu.textContent = dangqianshuzu.电机转速;    //电机转速：20prm
                       dianjiwendu.textContent = dangqianshuzu.电机温度;    //电机温度：10℃
                       dianjidianliou.textContent = dangqianshuzu.电机电流;    //电机电流：10A
                       qianduojidianya.textContent = dangqianshuzu.前舵机电压;    ////前舵机电压
                       qianduojiwendu.textContent = dangqianshuzu.前舵机温度;    ////前舵机温度
                       qianduojidianliou.textContent = dangqianshuzu.前舵机电流;    // //前舵机电流
                       qianduojiweizhi.textContent = dangqianshuzu.前舵机位置 ;    //前舵机位置  
                       qianduojiweitiaozhi.textContent = dangqianshuzu.前舵机微调值;    //前舵机微调值
                  








                       // console.log(dangqianshuzu)
                        // jiaotongquanbushebei.textContent = geshu;    //修改设备的总个数
                        // jiaotongdangqianhao.textContent = dangqianjian;    //当前设备号
                        // //jiaotongdangqianmoshi.textContent = dangqianshuzu.图片文字;    //图片文字
                        // //jiaotongdizhi.textContent = dangqianshuzu.地区;    //理工大学
                        // jiaotongtupian.src = dangqianshuzu.链接;    //修改图片
                         








                }   
                //激光雷达
                else if(topic == "jiguangleida"){
                  const jsonData = JSON.parse(message.toString());               
                  const keys = Object.keys(jsonData);
                  // console.log(jsonData)
                  const allKeys = Object.keys(jsonData);
                  //console.log(allKeys[0],'小车的号码')
                  
                  if(allKeys[0]==1){//控制一号车
                     //console.log(jsonData[allKeys[0]],'我是二号车');
                    var x = Math.round(jsonData[allKeys[0]].x * 1000) / 3.96 ;
                    var y = Math.round(jsonData[allKeys[0]].y * 1000) / 3.88; 
                    //判断x -10
                    if( 0<= y && y <=494){
                      y = 504-y;
                    }
                    else if(494 < y  && y <= 504){
                      y = -(504-y) ;
                    }
                    else if(y<0){
                      y=0
                    }else if(y>504){
                      y=504
                    }
                    if(0<=x  && x<=720){
                      x = x;
                    }else if(x>720){
                      x=720
                    }else if(x<0){
                      x=0
                    }
                    console.log(jsonData[allKeys[0]].x  ,'我是x')
                    //console.log(y ,'我是y')
                    xiaocheweizi1.style.top =`${y}px`; // 距离父元素顶部100px
                    xiaocheweizi1.style.left = `${x}px`; // 距离父元素左侧200px

                  }
                  else if(allKeys[0] == 2){//控制二号车
                    //console.log(jsonData[allKeys[0]],'我是二号车');
                    var x = Math.round(jsonData[allKeys[0]].x * 1000) / 3.96 ;
                    var y = Math.round(jsonData[allKeys[0]].y * 1000) / 3.88; 
                    //判断x -10
                    if( 0<= y && y <=494){
                      y = 504-y;
                    }
                    else if(494 < y  && y <= 504){
                      y = -(504-y) ;
                    }
                    else if(y<0){
                      y=0
                    }else if(y>504){
                      y=504
                    }
                    if(0<=x  && x<=720){
                      x = x;
                    }else if(x>720){
                      x=720
                    }else if(x<0){
                      x=0
                    }
                    console.log(jsonData[allKeys[0]].x  ,'我是x')
                    //console.log(y ,'我是y')
                    xiaocheweizi2.style.top =`${y}px`; // 距离父元素顶部100px
                    xiaocheweizi2.style.left = `${x}px`; // 距离父元素左侧200px
                  } 
                    else if(allKeys[0] == 3){//控制二号车
                    //console.log(jsonData[allKeys[0]],'我是二号车');
                    var x = Math.round(jsonData[allKeys[0]].x * 1000) / 3.96 ;
                    var y = Math.round(jsonData[allKeys[0]].y * 1000) / 3.88; 
                    //判断x -10
                    if( 0<= y && y <=494){
                      y = 504-y;
                    }
                    else if(494 < y  && y <= 504){
                      y = -(504-y) ;
                    }
                    else if(y<0){
                      y=0
                    }else if(y>504){
                      y=504
                    }
                    if(0<=x  && x<=720){
                      x = x;
                    }else if(x>720){
                      x=720
                    }else if(x<0){
                      x=0
                    }
                    console.log(jsonData[allKeys[0]].x  ,'我是x')
                    //console.log(y ,'我是y')
                    xiaocheweizi3.style.top =`${y}px`; // 距离父元素顶部100px
                    xiaocheweizi3.style.left = `${x}px`; // 距离父元素左侧200px
                  } 



                }
                // 尝试解析JSON格式消息
                try {
                   
                } catch (e) {
                    // 如果不是JSON格式，不做处理
                }
            });

            // 连接错误处理
            client.on('error', (err) => {
                console.error('❌ 连接错误:', err);  
                duankai(); // 出错时自动断开
            });

            // 意外断开连接处理
            client.on('close', () => {
                if (isConnected) {
                    isConnected = false;
                    updateUI();
                    console.log('🔌 连接已意外断开');
                }
            });
        }

        // 断开连接函数
        function duankai() {
            console.log('尝试断开设备连接...')
            if (client && isConnected) {
                client.end();
                isConnected = false;
                updateUI();
                console.log('🔌 已断开与华为云IoT的连接');
                client = null;
            }
        }

        // 更新UI状态
        function updateUI() {
            if (isConnected) {
               
             
            } else {
             
             
            }
        }

 
//建筑灯光-------------------------------------------------------------------------------------------

  // 1. 获取 DOM 元素
        const videoElement = document.getElementById('whep-player');
        const loadingEl = document.getElementById('loading');
        const errorEl = document.getElementById('error');
        const errorTextEl = document.getElementById('error-text');
        const retryBtn = document.getElementById('retry-btn');

        // 2. 你的 WHEP 拉流地址（已填入你提供的地址）
        //const whepStreamUrl = 'http://8.155.164.202:2022/rtc/v1/whep/?app=live&stream=livestream';
        const whepStreamUrl = 'http://8.155.164.202:2022/rtc/v1/whep/?app=live&stream=livestream';
        // 3. 核心：建立 WHEP 协议连接并拉流
        async function connectWHEPStream() {
            // 显示加载状态，隐藏错误状态
            loadingEl.style.display = 'flex';
            errorEl.style.display = 'none';

            try {
                // 步骤1：创建 RTCPeerConnection（WebRTC 核心对象）
                const pc = new RTCPeerConnection({
                    iceServers: [
                        // 公共 STUN 服务器（帮助设备穿透 NAT，获取公网地址）
                        { urls: 'stun:stun.l.google.com:19302' },
                        { urls: 'stun:stun1.l.google.com:19302' }
                    ]
                });

                // 步骤2：监听媒体流轨道（当收到流时，绑定到 video 元素）
                pc.ontrack = (event) => {
                    if (event.streams && event.streams[0]) {
                        videoElement.srcObject = event.streams[0];
                        loadingEl.style.display = 'none'; // 加载成功，隐藏加载提示
                    }
                };

                // 步骤3：监听连接状态变化（处理异常）
                pc.oniceconnectionstatechange = () => {
                    const state = pc.iceConnectionState;
                    if (state === 'failed' || state === 'disconnected' || state === 'closed') {
                        throw new Error(`连接状态异常：${state}`);
                    }
                };

                // 步骤4：创建 SDP Offer（WebRTC 连接的“请求信号”）
                const offer = await pc.createOffer({
                    offerToReceiveAudio: true, // 接收音频（如需纯视频可设为 false）
                    offerToReceiveVideo: true  // 接收视频
                });
                await pc.setLocalDescription(offer);

                // 步骤5：通过 HTTP POST 发送 Offer 到 WHEP 服务器（WHEP 协议核心步骤）
                const response = await fetch(whepStreamUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/sdp', // SDP 是 WebRTC 媒体协商的格式
                        'Accept': 'application/sdp'
                    },
                    body: pc.localDescription.sdp // 发送本地 SDP Offer
                });

                // 步骤6：处理服务器响应，完成连接
                if (!response.ok) {
                    throw new Error(`服务器响应失败：${response.status} ${response.statusText}`);
                }
                const remoteSdp = await response.text();
                await pc.setRemoteDescription(new RTCSessionDescription({
                    type: 'answer', // 服务器返回的是“应答”信号
                    sdp: remoteSdp
                }));

                // 步骤7：页面关闭时销毁连接（释放资源）
                window.addEventListener('beforeunload', () => {
                    pc.close();
                });

            } catch (err) {
                // 捕获所有错误，显示错误提示
                loadingEl.style.display = 'none';
                errorTextEl.textContent = `拉流失败：${err.message}`;
                errorEl.style.display = 'flex';
                console.error('WHEP 拉流错误：', err);
            }
        }

        // 4. 重试按钮绑定事件
        retryBtn.addEventListener('click', connectWHEPStream);

        // 5. 页面加载完成后自动启动拉流
        window.addEventListener('load', connectWHEPStream);
